import { BaseService, CoolCommException } from "@cool-midway/core";
import { Provide, Provider } from "@midwayjs/core";
import { InjectEntityModel } from "@midwayjs/typeorm";
import { Repository } from "typeorm";
import { CityInfoEntity } from "../entity/info";

@Provide()
export class CityInfoService extends BaseService {

    @InjectEntityModel(CityInfoEntity)
    cityInfoEntity: Repository<CityInfoEntity>;

    /**
     * 根据父级ID获取城市列表
     * @param parentId 父级ID
     * @returns 城市列表
     */
    async getCityListByParentId(parentId: number) {
        const queryBuilder = this.cityInfoEntity.createQueryBuilder('city');
        queryBuilder.where('city.parentId = :parentId', { parentId });
        queryBuilder.orderBy('city.createTime', 'DESC');
        const list = await queryBuilder.getMany();
        return list;
    }

    /**
     * 根据首字母获取城市列表
     * @param firstLetter 首字母
     * @returns 城市列表
     */
    async getCityListByFirstLetter(firstLetter: string) {
        const queryBuilder = this.cityInfoEntity.createQueryBuilder('city');
        queryBuilder.where('city.firstLetter = :firstLetter', { firstLetter });
        queryBuilder.orderBy('city.createTime', 'DESC');
        const list = await queryBuilder.getMany();
        return list;
    }

    /**
     * 根据拼音获取城市列表
     * @param pinyin 拼音
     * @returns 城市列表
     */
    async getCityListByPinyin(pinyin: string) {
        const queryBuilder = this.cityInfoEntity.createQueryBuilder('city');
        queryBuilder.where('city.pinyin = :pinyin', { pinyin });
        queryBuilder.orderBy('city.createTime', 'DESC');
        const list = await queryBuilder.getMany();
        return list;
    }

    /**
     * 设置城市封面
     * @param id 城市ID
     * @param cover 封面
     * @returns 城市
     */
    async setCover(id: number, cover: string) {
        const cityInfo = await this.cityInfoEntity.findOne({ where: { id: id } });
        if (!cityInfo) {
            throw new CoolCommException('城市不存在');
        }
        cityInfo.cover = cover;
        return await this.cityInfoEntity.save(cityInfo);
    }

}